const imgValue = [['camera'], ['album'], ['camera', 'album']] // '拍照', '相册', '拍照或相册'
const uploadFileUrl = require('./utils/api').uploadFileUrl;
var server = require('./utils/server');
App({
	onLaunch: function () {
		var self = this;
		var rd_session = wx.getStorageSync('rd_session');
		if (!rd_session) {
			self.login();
		} else {
			wx.checkSession({
				success: function (e) {
					// 登录态未过期
					console.log('登录态未过期')
					self.rd_session = rd_session;
					self.getUserInfo();
				},
				fail: function () {
          //登录态过期
          console.log('登录态过期')
          self.login();
				}
			})
		}
	},
	onShow: function () {
		// console.log('App Show')
	},
	onHide: function () {
		// console.log('App Hide')
  },
  rd_session: null,
	globalData: {
		hasLogin: false
	},
	login: function() {
		var self = this;
		wx.login({
			success: function (res) {
        server.getJSON('openIdUrl', {code: res.code}, function (res) {
          wx.setStorageSync('rd_session', res.data.data.rd_session)
          self.rd_session = res.data.data.rd_session;
					self.globalData.hasLogin = true;
					self.getUserInfo();
				});
			}
		});
	},
	getUserInfo: function(fn) {
		var self = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              // console.log('getUserInfo', res)
              self.globalData.userInfo = res.userInfo;
              server.postJSON('authLogin', {
                rd_session: self.rd_session,
                result: res
              }, function (e) {
                if (e.data.status === 200) {
                  // TODO:成功返回
                  wx.setStorageSync('token', e.data.data.token);
                  wx.setStorageSync('oauth', e.data.data.oauth);
                  fn && fn(e.data.data);
                } else if (e.data.status === 201){
                  self.login();
                }
              });
            },
            fail: function (e) {
              console.log(e)
            }
          });
        }
      }
    })
	},
  sourceTypeChange: function(a, c, fn) { // 上传图片事件
    var that = this
    wx.chooseImage({
      sourceType: imgValue[a],
      sizeType: ['compressed'],
      count: c,
      success: function (res) {
        res.tempFiles.forEach((ele) => {
          if (ele.size > 10485760) {
            wx.hideLoading()
            return wx.showToast({
              icon: 'none',
              mask: true,
              duration: 1000,
              title: "图片太大,上传失败"
            })
          }
          var uploadTask = wx.uploadFile({
            url: uploadFileUrl,
            filePath: ele.path,
            name: 'file',
            formData: {
              'file': ele,
              'token': wx.getStorageSync('userData').token
            },
            success: function (resed) {
              switch (resed.statusCode) {
                case 504:
                  return wx.showToast({
                    image: '../../../image/jingao.png',
                    mask: true,
                    duration: 1000,
                    title: "上传超时"
                  })
                case 500:
                  return wx.showToast({
                    image: '../../../image/jingao.png',
                    mask: true,
                    duration: 1000,
                    title: "上传错误"
                  })
                case 200:
                  let dataUrl = JSON.parse(resed.data)
                  if (dataUrl.status === 200) {
                    var arr = {};
                    arr.dataFiles = [];
                    arr.tempFiles=[];
                    arr.dataFiles.push(dataUrl.filename)
                    arr.tempFiles.push(ele.path)
                    wx.showToast({
                      title: "上传成功",
                      icon: "success",
                      duration: 1000,
                      mask: true
                    })
                    fn && fn(arr);
                  }
                  break;
                default:
                  wx.hideLoading();
              }
            },
            fail: function (res) {
              wx.hideLoading()
              wx.showToast({
                image: '../../../image/jingao.png',
                mask: true,
                duration: 1000,
                title: "上传失败"
              })
            }
          })
          uploadTask.onProgressUpdate((res) => {
            wx.showLoading({
              title: '上传中' + res.progress,
            })
            // console.log('上传进度', res.progress)
            // console.log('已经上传的数据长度', res.totalBytesSent)
            // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
          })
        })
      }
    })
  },
})
